import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Popconfirm } from 'antd';
import { useRef, useState } from 'react';
import { connect, useModel } from 'umi';
import { PageContainer } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
// 详情页组件
import Description from '@/pages/common/description';
import ModalFormItem from './detail';
import Authorized from '@/components/Authorized';


// 商户id
const merchant_role = "614547299561123840";

// 用户列表
const SysUser = ({ dispatch, loading }: {

  dispatch: any;
  loading: boolean;
}) => {
  const actionRef = useRef<ActionType>();
  const formRef = useRef<any>();
  // tableList 数据源
  const [dataSource, setDataSource] = useState<{ data?: any[]; success?: boolean; total?: number; }>({
    data: [],
    success: true,
    total: 0
  });
  // 新增|编辑 窗口显示状态
  const [formModalVisible, handleModalVisible] = useState<boolean>(false);
  // 是否展示详情窗口
  const [showDetail, setShowDetail] = useState<boolean>(false);
  // 当前项的数据
  const [currentRow, setCurrentRow] = useState<API.RuleListItem>();
  // 是否是编辑
  const [isEdit, setIsEdit] = useState<boolean>(false);

  const { initialState } = useModel('@@initialState');


  const columns: ProColumns<API.RuleListItem>[] = [
    {
      title: '用户名',
      dataIndex: 'username',
    },
    {
      title: '用户昵称',
      dataIndex: 'nickName',
    },
    // {
    //   title: '手机号',
    //   dataIndex: 'mobile',
    // },
    {
      title: '状态',
      valueEnum: {
        0: {
          text: '正常',
        },
        1: {
          text: '停用',
        }
      },
      dataIndex: 'status',
      renderText: (text: number, row) => {

        if (text === 1) {
          return "停用";
        } else {
          if (new Date().getTime() < new Date(row.userLockTime).getTime()) {
            return "锁定";
          }
          return "正常";

        }
      }
    },

    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      hideInDescriptions: true,
      render: (_, record, index) => {
        const { roleIdList } = record;
        const { currentUser } = initialState || {};

        const { userid, merchantId } = currentUser || {};

        // 自己不能修改自己。
        const optionList = [];
        optionList.push(<Button type="link"
          key="detail"
          onClick={() => {
            record.showName = record.username;
            setCurrentRow(record);
            setShowDetail(true);
          }}
        >
          查看
        </Button>);
        let edit = true;
        if (userid == record.id) {
          edit = false;
        } else if (record.id == 1) {
          // 是系统管理员。
          edit = false;
        } else if (merchantId != '0' && roleIdList.includes(merchant_role)) {
          // 商户列表，且是商户管理员。
          edit = false;
        }
        if (edit) {
          optionList.push(
            <Authorized authority="sysuser:update">
              <Button type="link"
                key="edit"
                onClick={() => {
                  handleModalVisible(true);
                  setIsEdit(true);
                  setCurrentRow(record);
                }}
              >
                编辑
              </Button>
            </Authorized>
          );
          optionList.push(
            <Authorized authority="sysuser:update">
              <Popconfirm title={`确定${record.status === 1 ? '启用' : '停用'}吗?`} onConfirm={() => updateStatus(record.id, record.status === 1 ? 0 : 1)}>
                <Button type="link">{record.status === 1 ? '启用' : '停用'}</Button>
              </Popconfirm>
            </Authorized>
          );
          if (new Date().getTime() < new Date(record.userLockTime).getTime()) {
            optionList.push(
              <Authorized authority="sysuser:update">
                <Popconfirm title="确定解锁吗?" onConfirm={() => unlockUser(record.id)}>
                  <Button type="link">解锁</Button>
                </Popconfirm>
              </Authorized>
            );
          }
        }

        return optionList;
      },
    },
  ];
  // 删除
  const deleteRecord = (record: any) => {
    const hide = message.loading('停用中');
    dispatch({
      type: 'sysUser/fakeDelete',
      payload: { id: record.id },
      callback: (res: any) => {
        if (res.code === 1) {
          hide();
          message.success('停用成功');
          actionRef.current?.reload();

        } else {
          hide();
          message.error(res.msg);
          return false;
        }

      }
    });
  }

  const updateStatus = (id: string, status: number) => {
    dispatch({
      type: 'sysUser/updateStatus',
      payload: { id, status },
      callback: (e) => {
        if (e.code === 1) {
          message.success('操作成功');
          actionRef.current?.reload();
        } else {
          message.error(e.msg || '操作失败');
        }
      }
    });
  }

  const unlockUser = (id: string) => {
    dispatch({
      type: 'sysUser/unlockUser',
      payload: id,
      callback: (e) => {
        if (e.code === 1) {
          message.success('操作成功');
          actionRef.current?.reload();
        } else {
          message.error(e.msg || '操作失败');
        }
      }
    });
  }

  // 列表查询
  const findPage = async (params: any) => {

    return new Promise((res, rej) => {
      dispatch({
        type: 'sysUser/findPage',
        payload: params,
        callback: (response: any) => {
          if (response.code === 1) {
            const { list: data, total } = response;
            res({ data, total, success: true });
          } else {
            // 这里需要清空
            res({ data: [], total: 0, success: true });
          }

        }
      });
    });
  }

  return (
    <div>
      <ProTable
        options={false}
        headerTitle={''}
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Authorized authority="sysuser:save">
            <Button
              type="primary"
              key="primary"
              onClick={() => handleModalVisible(true)}
            >
              <PlusOutlined /> 新建
            </Button>
          </Authorized>
        ]}
        request={(params: any) => {
          return findPage(params)
        }}
        columns={columns}
        pagination={{ pageSize: 10 }}
      />


      {/* 新增、编辑 */}
      <ModalFormItem
        isEdit={isEdit}
        currentRow={currentRow}
        formModalVisible={formModalVisible}
        handleModalVisible={(e: boolean) => {

          if (!e) {
            setIsEdit(e); // 修改为非编辑状态
            formRef?.current?.resetFields();// 情况表单上的值
          }
          handleModalVisible(e)
        }}
        setDataSource={(e: { data?: any[]; success?: boolean; total?: number; }) => setDataSource(e)}
        dataSource={dataSource}
        actionRef={actionRef}
        formRef={formRef}
        loading={loading}
      />

      {/* 详情查看 */}
      <Description
        showDetail={showDetail}
        setCurrentRow={(e: any) => setCurrentRow(e)}
        setShowDetail={(e: any) => setShowDetail(e)}
        currentRow={currentRow}
        columns={columns}
      />

    </div>
  );
};

export default connect(
  ({ loading }: { index: any; loading: any }) => ({

    loading: loading.models.sysUser,
  }),
)(SysUser);
